package com.pig4cloud.pigx.contract.executer.order.matcher;

import com.pig4cloud.pigx.common.customize.exception.MqAckException;
import com.pig4cloud.pigx.contract.constant.OrderExecutorErrorMsg;
import com.pig4cloud.pigx.contract.mongo.entity.ContractOrderMongo;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 订单撮合器管理器
 *
 * @since 2022/8/17 11:12
 */
@Data
@Slf4j
@Component
public class OrderMatcherManager {

	/**
	 * 订单撮合器集合
	 */
	private final List<OrderMatcher> matcherList = new ArrayList<>();

	/**
	 * 撮合订单
	 *
	 * @param msg 消息
	 * @since 2022/8/17 11:15
	 */
	public void match(ContractOrderMongo msg) {
		ContractOrderMongo taker = null;
		for (OrderMatcher i : matcherList) {
			try {
				if (Objects.isNull(taker)) {
					taker = i.getOrder(msg.getId(), msg.getIsBuy());
				}

				if (!i.support(taker)) {
					continue;
				}

				i.match(taker);
				i.success(taker);
				return;
			} catch (Exception e) {
				i.fail(taker, e);
				log.error(OrderExecutorErrorMsg.ORDER_MATCH_ERROR, e.getMessage());

				if (e instanceof MqAckException) {
					return;
				}
				throw e;
			}
		}

		throw new RuntimeException(OrderExecutorErrorMsg.ORDER_MATCH_NOT_MATCH);
	}
}
